class IndexedDB {
  constructor() {
    this.tableName = 'user';
    this.connection = null;
    this.store = null;
    this.createIndexedDb();
  }


  createIndexedDb() {
    const self = this;
    this.db = window.indexedDB.open('myDatabase');
    this.db.onupgradeneeded = function (event) {
      console.log('===========>onupgradeneeded', event);
      self.connection = event.target.result;
      if(!self.connection.objectStoreNames.contains(self.tableName)) {
        self.createUserTable();
      }

      // backupUserTable();
    }

    // 下次打开数据库时触发
    this.db.onsuccess = function (event)  {
      console.log('===========>onsuccess', event);
      self.connection = event.target.result;
      self.backupUserTable();
    }
    this.db.onerror = function () {

    }
  }


  // 回滚数据
  restoreUserTable() {
    this.createTransaction();
    const store = this.store;
    const backup = JSON.parse(localStorage.getItem('backupData') || '{}');
    Object.keys(backup).forEach(key => {
      store.put(backup[key]);
    });
    localStorage.removeItem('backupData');
  }

  // 备份用户表
  backupUserTable() {
    const transaction = this.connection.transaction(this.tableName, 'readonly');
    const store = transaction.objectStore(this.tableName);
    const data = {};
    store.openCursor().onsuccess = function(event) {
      const cursor = event.target.result;
      if (cursor) {
        data[cursor.key] = cursor.value;
        cursor.continue();
      } else {
        // 在这里 data 变量包含了所有的备份数据
        localStorage.setItem('backupData', JSON.stringify(data));
      }
    };
  }

  createUserTable() {
    this.connection.createObjectStore(this.tableName, {
      keyPath: 'user_id', // 指定主键
    });
  }


  // 创建事物
  createTransaction() {
    const tx = this.connection.transaction(this.tableName, 'readwrite');
    this.store = tx.objectStore(this.tableName);
    return this.store;
  }


  addUser(user_id, data) {
    const self = this;
    this.createTransaction();
    const addReq = this.store.add({
      user_id: user_id || '1',
      ...(data || {})
    });

    addReq.onsuccess = function() {
      self.backupUserTable();
    }
  }

  updateUser(content) {
    const self = this;
    this.createTransaction();
    const putReq = this.store.put({
      user_id: '1',
      ...content
    });

    putReq.onsuccess = function() {
      self.backupUserTable();
      console.log('========>修改成功！');
    }
  }

  getUser(user_id) {
    return new Promise((resolve, reject) => {
      this.createTransaction();
      const getReq = this.store.get(user_id || '1');
      getReq.onsuccess = function(event) {
        const data = event.target.result;
        console.log('========>读取成功！', data);
        resolve(data);
      }
      
      getReq.onerror = function(error) {
        console.log('========>读取失败！', error);
        reject();
      };
    });
  }

  deleteUser(user_id) {
    return new Promise((resolve, reject) => {
      this.createTransaction();
      const deleteReq = this.store.delete(user_id || '1');

      deleteReq.onsuccess = function(event) {
        // const data = event.target.result;
        console.log('========>删除成功！', event);
        resolve();
      }

      deleteReq.onerror = function () {
        reject();
      };

    });
    
  }


};